package com.assets.Shift;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.assets.Adapter.Input_Adapter_item1;
import com.assets.Allot.ReceivingDepartment;
import com.assets.Check.newTanWanCheck.BaseActivity1;
import com.assets.Receive.add_admin;
import com.assets.Receive.add_recipient;
import com.assets.bean.Input_item1;
import com.assets.newNHF.util.LogUtils;
import com.assets.util.MyRFIDHandle;
import com.assets.util.RFIDClientUtil;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Scan.qrcode.util.Constant;
import com.assets.Scan.zxing.activity.CaptureActivity;
import com.assets.CanniBalize.Shift_site;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Allot_Add extends BaseActivity1 implements OnDismissListener {
    private ImageView imageView;
    private LinearLayout ll_user;
    private Button up_bt, scan_img, btn_rfid;//上传数据，扫码
    private List<String> date = new ArrayList<>();
    private List<Input_item1> data = new ArrayList<>();//扫码
    private List<String> assetId = new ArrayList<>();//资产id
    private EditText allot_remark, et_num;//备注
    private ListView lv_list;
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private Allot_Add content;
    private String placeId = "";
    private String url_up = "http://" + Url.IP + "/api/transferAdd";//上传
    private String url = "http://" + Url.IP + "/api/assetScanTransferQuery";//获取资产信息url
    private String company_id = "", division_id = "", userId = "", dept_id = "", managerId = "";//转移单位，转移部门，接收人id
    private TextView company_name, select_department, tv_place, title_text, tv_user, tv_dept, select_manager;//转移单位，转移部门，接收人name
    private LinearLayout company, call_department, site_ll, ll_dept;//转移单位转移部门，接收人,使用部门

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.allot_add);
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        content = this;
        date.clear();
        lv_data.clear();
        inview();
        et_num.setFocusableInTouchMode(true);
        et_num.requestFocus();
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable S) {
                et_num.selectAll();
                for (int i = 0; i < data.size(); i++) {
                    if (et_num.getText().toString().trim().equals(data.get(i).getCode_number())) {
                        Toast.makeText(content, "该资产已存在列表", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (!et_num.getText().toString().trim().equals("") && et_num.length() > 9) {
                    if (!lv_data.contains(et_num.getText().toString().trim())) {
                        post(et_num.getText().toString().trim(), "");
                    } else {
                        Toast.makeText(content, "该资产已存在列表", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    Toast.makeText(content, "错误的格式", Toast.LENGTH_SHORT).show();
                }
            }
        });


        //公司
        company.setOnClickListener(v -> {
            tv_user.setText("");
            userId = "";
            division_id = "";
            select_department.setText("");
            Intent dept = new Intent(content, Allot_unit.class);
            startActivityForResult(dept, 1);
        });
        //事业部
        call_department.setOnClickListener(v -> {
            if (!company_name.getText().toString().equals("")) {
                tv_user.setText("");
                userId = "";
                Intent intent = new Intent(content, Allot_department.class);
                intent.putExtra("department_id", company_id);
                startActivityForResult(intent, 2);
            }
        });
        //使用部门
        ll_dept.setOnClickListener(v -> {
            Intent intent = new Intent(this, ReceivingDepartment.class);
            intent.putExtra("deptId", division_id);
            startActivityForResult(intent, 3);
        });
        //接收人
        ll_user.setOnClickListener(v -> {
            if (!select_department.getText().toString().equals("")) {
                Intent intent = new Intent(Allot_Add.this, add_recipient.class);
                intent.putExtra("department_id", dept_id);
                startActivityForResult(intent, 4);
            }
        });
        //存放位置
        site_ll.setOnClickListener(v -> {
            Intent intent = new Intent(content, Shift_site.class);
            startActivityForResult(intent, 5);
        });
        up_bt.setOnClickListener(v -> {
            if (data.size() <= 0) {
                Toast.makeText(content, "请扫码需要转移的资产", Toast.LENGTH_SHORT).show();
                return;
            }

            if (company_id.equals("") || division_id.equals("") || tv_user.getText().toString().trim().equals("")) {
                Toast.makeText(content, "请完善数据", Toast.LENGTH_SHORT).show();
                return;
            }
            new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    //取消：position=-1,确定 position=0
                    if (position == 0) {
                        assetId.clear();
                        for (int i = 0; i < data.size(); i++) {
                            assetId.add(data.get(i).getCode_number());
                        }
                        upload();
                    }
                    if (position == -1) {

                    }

                }
            }).setCancelable(true).setOnDismissListener(content).show();
        });
    }

    private void inview() {
        et_num = (EditText) findViewById(R.id.et_num);
        ll_user = (LinearLayout) findViewById(R.id.allot_recipient);
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("添加转移单");
        tv_place = (TextView) findViewById(R.id.site_tv);
        site_ll = (LinearLayout) findViewById(R.id.site_ll);
        lv_list = (ListView) findViewById(R.id.fragment2_list);
        scan_img = (Button) findViewById(R.id.scan_img);
        call_department = (LinearLayout) findViewById(R.id.call_department);
        company = (LinearLayout) findViewById(R.id.fold_unit);
        ll_dept = findViewById(R.id.ll_dept);
        tv_user = (TextView) findViewById(R.id.recipient);
        select_manager = findViewById(R.id.select_manager);
        select_manager.setOnClickListener(v -> {
            if (TextUtils.isEmpty(company_id)) {
                showToast("请先选择公司");
                return;
            }
            Intent intent = new Intent(content, add_admin.class);
            intent.putExtra("company_id", company_id);
            startActivityForResult(intent, 4);
        });
        tv_dept = findViewById(R.id.tv_dept);
        company_name = (TextView) findViewById(R.id.fold_section);
        select_department = (TextView) findViewById(R.id.select_department);
        up_bt = (Button) findViewById(R.id.allot_upload);
        allot_remark = (EditText) findViewById(R.id.allot_remark);
        imageView = (ImageView) findViewById(R.id.fh);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        scan_img.setOnClickListener(v -> {
            startQrCode();
        });
        lv_list.setOnItemLongClickListener((parent, view, position, id) -> {
            showTipDialog(aBoolean -> {
                if (aBoolean){
                    lv_data.remove(data.get(position).getCode_number());
                    data.remove(position);
                    Input_Adapter_item1 adapter_item = new Input_Adapter_item1(content, R.layout.input_adapter_item, data);
                    lv_list.setAdapter(adapter_item);
                }
            },"确定删除");

            return true;
        });
        btn_rfid = findViewById(R.id.btn_rfid);
        btn_rfid.setOnClickListener(v -> {
            String rfidTitle = btn_rfid.getText().toString();
            if (rfidTitle.equals("开始读取")) {
                rfidClientUtil.read();
            } else {
                rfidClientUtil.stop();
            }
        });
        initRFID();
    }

    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(content, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onDismiss(Object o) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {
            company_id = data.getExtras().getString("company_id");
            String name = data.getExtras().getString("company_name");
            company_name.setText(name);
            LogUtils.d("公司名称" + name + "id" + company_id);
        }
        if (requestCode == 2 && resultCode == 2) {
            division_id = data.getExtras().getString("dept_id");
            String name = data.getExtras().getString("dept_name");
            select_department.setText(name);
            LogUtils.d("部门名称" + name + "id" + division_id);
        }
        //接收部门
        if (requestCode == 3 && resultCode == 2) {
            dept_id = data.getExtras().getString("dept_id");
            String name = data.getExtras().getString("dept_name");
            tv_dept.setText(name);
            LogUtils.d(dept_id + name);
        }
        //接收人
        if (requestCode == 4 && resultCode == 3) {
            userId = data.getExtras().getString("recipient_id");
            String name = data.getExtras().getString("recipient_name");
            tv_user.setText(name);
        }
        //管理人
        if (requestCode == 4 && resultCode == 7) {
            managerId = data.getExtras().getString("admin_id");
            String name = data.getExtras().getString("admin_name");
            select_manager.setText(name);
            LogUtils.d(managerId + name);
        }
        if (requestCode == 5 && resultCode == 3) {
            tv_place.setText(data.getExtras().getString("site_name"));
            placeId = data.getExtras().getString("site_id");
        }
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            if (!lv_data.contains(scanResult)) {

                post(scanResult, "");
            } else Toast.makeText(content, "该资产已存在列表", Toast.LENGTH_SHORT).show();
        }
    }

    private void post(final String assetNumber, final String rfid) {
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient
                    .Builder()
                    .hostnameVerifier(new AllowAllHostnameVerifier())
                    .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                    .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                    .readTimeout(500, TimeUnit.SECONDS)
                    .build();//创建OkHttpClient对象。
            FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
            formBody.add("assetNumber", assetNumber)
                    .add("rfid", rfid)
                    .add("userId", Since_case.getInstance().getUserId());
            Request request = new Request.Builder()//创建Request 对象。
                    .url(url)
                    .post(formBody.build())//传递请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //回调方法的使用与get异步请求相同
                    Log.i("123123", "error");
                    if (!TextUtils.isEmpty(rfid)) {
                        Allot_Add.this.map.remove(rfid);
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String responseData = response.body().string();
                    LogUtils.d(responseData);
                    //回调方法的使用与get异步请求相同
                    try {
                        JSONObject jsonObject = new JSONObject(responseData);
                        if (jsonObject.getString("state").equals("1")) {
                            JSONObject json = jsonObject.getJSONObject("asset");
                            String assetName = json.getString("assetName");
                            String deptId = json.getString("deptId");
                            String assetNumber1 = json.getString("assetNumber");
                            if (lv_data.contains(assetNumber1)) {
                                showToast("该资产已存在列表");
                                return;
                            }
                            lv_data.add(assetNumber1);
                            String userId = json.getString("userId");
                            String model = json.getString("model");
                            String type = json.getString("type");
                            String image = json.getString("image");
                            if (!TextUtils.isEmpty(image)) {
                                image = "http://" + Url.IP + image;
                            }
                            data.add(0,new Input_item1(image, assetName, deptId, assetNumber1, userId, model, type, ""));
                            Input_Adapter_item1 adapter_item = new Input_Adapter_item1(content, R.layout.input_adapter_item, data);
                            runOnUiThread(() -> {
                                lv_list.setAdapter(adapter_item);
                                Toast.makeText(content, "添加成功", Toast.LENGTH_SHORT).show();
                            });
                        }
                        if (jsonObject.getString("state").equals("0")) {
                            showToast("失败");
                        }
                        if (jsonObject.getString("state").equals("2")) {
                            showToast("资产不存在");
                        }
                        if (jsonObject.getString("state").equals("3")) {
                            showToast("当前资产不可转移");
                        }
                        if (jsonObject.getString("state").equals("4")) {
                            showToast("用户无权限操作此资产");
                        }
                    } catch (JSONException e) {
                        LogUtils.d("转移资产解析异常"+e.getMessage());
                        e.printStackTrace();
                    }
                }
            });
        }).start();
    }

    private void upload() {
        OkHttpClient client = new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("inunit", company_id)//公司
                .add("userId", Since_case.getInstance().getUserId())
                .add("place", placeId)//存放位置
                .add("assetNumbers", String.valueOf(assetId))//二维码
                .add("division", division_id)//事业部
                .add("indept", dept_id)//使用部门
                .add("inuser", userId)//使用人
                .add("admin", managerId)//管理人
                .add("remark", allot_remark.getText().toString()); //传递键值对参数
        LogUtils.d("公司:" + company_id + "存放位置" + placeId + "assetNumbers" + assetId + "事业部" + division_id + "转入部门" + dept_id + "使用人" + userId);
        Request request = new Request.Builder()//创建Request 对象。
                .url(url_up)
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //回调方法的使用与get异步请求相同
                LogUtils.d("error");
                showToast("连接服务器失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseData = response.body().string();
                LogUtils.d(responseData);
                //回调方法的使用与get异步请求相同
                try {
                    JSONObject jsonObject = new JSONObject(responseData);
                    if (jsonObject.getString("state").equals("1")) {
                        showToast("提交成功");
                        finish();
                    }
                    if (jsonObject.getString("state").equals("0")) {
                        showToast("提交失败");
                    }
                } catch (JSONException e) {
                    showToast("解析异常");
                    e.printStackTrace();
                }
            }
        });
    }

    private RFIDClientUtil rfidClientUtil;
    private Map<String, String> map = new HashMap<>();

    private void initRFID() {
        MyRFIDHandle myRFIDHandle = new MyRFIDHandle();
        myRFIDHandle.post(() -> {
            rfidClientUtil = new RFIDClientUtil(epc -> {
                if (map.containsKey(epc)) {
                    return;
                }
                map.put(epc, "");
                post("", epc);
                //RFID(epc);
            });
            rfidClientUtil.setRequestStop(() -> runOnUiThread(() -> {
                btn_rfid.setText("开始读取");
            }));
            rfidClientUtil.setRequestRead(() -> runOnUiThread(() -> {
                btn_rfid.setText("停止读取");
            }));
            getLifecycle().addObserver(myRFIDHandle);
            getLifecycle().addObserver(rfidClientUtil);
        });
    }
}
